package org.apache.cocoon.transformation;

import java.io.IOException;
import java.util.Map;
import java.util.regex.Pattern;

import org.apache.avalon.framework.parameters.ParameterException;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.SourceResolver;
import org.xml.sax.SAXException;

/**
 * This is a sample Cocoon transformer for demonstrating CoUnit.
 * The transformer replaces text occurences that match a regular
 * expression by a given string. 
 * 
 * The transformer has no regexp options and will not function 
 * correctly in cases of long text strings, because text will
 * be split into several sax events, which is not taken into
 * account.
 * 
 * &gt;map:transform type="regexp"&lt;
 *   &gt;map:parameter name="regexp" value="po+p"/&lt;
 *   &gt;map:parameter name="replacement" value="meconium"/&lt;
 * &gt;/map:transform&lt;
 * 
 * @author JBoer
 *
 */

public class ReplaceByRegExpTransformer extends AbstractSAXTransformer {

	private static final String PARAM_REPLACEMENT = "replacement";
	private static final String PARAM_REGEXP = "regexp";
	private Pattern regexpPattern;
	private String replacement;

	public void setup(SourceResolver resolver, Map objectModel, String src, Parameters params) throws ProcessingException, SAXException, IOException {
		super.setup(resolver, objectModel, src, params);
		
		/* get the regular expression and replacement from the parameters */
		String regexp;
		try {
			regexp = params.getParameter(PARAM_REGEXP);
			replacement = params.getParameter(PARAM_REPLACEMENT);
		} catch (ParameterException e) {
			throw new ProcessingException(e);
		}

		regexpPattern = Pattern.compile(regexp); //no options for now
	}

	public void characters(char[] c, int pos, int length) throws SAXException {
		/* convert to string */
		String text = new String(c, pos, length);
		/* do replacement */
		text = regexpPattern.matcher(text).replaceAll(replacement);
		/* copy into new character array */
		char[] newC = new char[text.length()];
		text.getChars(0, text.length(), newC, 0);
		/* pass through */
		super.characters(newC, 0, text.length());
	}

	
}
